﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;
using System.IO;
using System.Net.Http.Headers;
using DevExpress.XtraGrid.Columns;
using static BW.Mes.WinForms.Process.ProcessDataForm;


namespace BW.Mes.WinForms.Production.Order
{
    public partial class UpdateOrderForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _OerderUrl = "https://localhost:7223";
        private readonly string _apiProcessUrl = "https://localhost:7222";
        private readonly string _apiBaseUrl = "https://localhost:7274";

        private OrderForm.WorkOrderModel _orderModel;

        /// <summary>
        /// 构造函数注入
        /// </summary>
        public UpdateOrderForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            _apiProcessUrl = "https://localhost:7222"; // 替换为您的实际API基础URL
            _apiBaseUrl = "https://localhost:7274";

            // 初始化文件对话框
            xtraOpenFileDialog1 = new XtraOpenFileDialog();
            xtraOpenFileDialog1.Filter = "所有文件 (*.*)|*.*|图片文件 (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png";
            xtraOpenFileDialog1.Title = "选择文件";

            // 绑定图片按钮点击事件
            Img.Click += Photo_Click;

        }

        public UpdateOrderForm(OrderForm.WorkOrderModel model)
        {
            InitializeComponent();
            _orderModel = model; //保存模型的引用


            // 初始化文件对话框
            xtraOpenFileDialog1 = new XtraOpenFileDialog();
            xtraOpenFileDialog1.Filter = "所有文件 (*.*)|*.*|图片文件 (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png";
            xtraOpenFileDialog1.Title = "选择文件";

            // 初始化HttpClient
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 先加载数据源
            _ = LoadInitialData();

            // 绑定图片按钮点击事件
            Img.Click += Photo_Click;

            if (model != null)
            {
                Code.Text = model.Code;
                ProductionType.Text = model.ProductionType;
                // Client和Line的值设置需要在数据加载后进行
                Masterdata.Text = model.Masterdata;
                Progress.Text = model.Progress;
                ProductionCount.Text = model.ProductionCount.ToString();
                BeginTime.DateTime = model.BeginTime;
                EndTime.DateTime = model.EndTime;
                Whether.EditValue = model.Whether;

                // 添加图片和备注的回显
                if (!string.IsNullOrEmpty(model.Img))
                {
                    try
                    {
                        // 显示文件名在按钮上
                        Img.Text = Path.GetFileName(model.Img);
                        // 保存完整URL在ToolTip中
                        Img.ToolTip = model.Img;
                    }
                    catch
                    {
                        // 如果解析文件名失败，直接显示URL
                        Img.Text = "已上传文件";
                        Img.ToolTip = model.Img;
                    }
                }
                else
                {
                    Img.Text = "选择文件";
                }

                ProductionDesc.Text = model.ProductionDesc;
            }
            // 加载初始数据（产线和客户数据）
            //_ = LoadInitialData();
        }


        private async Task LoadInitialData()
        {
            try
            {
                // 加载产线数据
                await ShowProcess();

                // 加载客户数据
                // await ShowClient();

                // 在数据加载完成后，设置选中值
                if (_orderModel != null)
                {
                    // 设置客户和产线的选中值
                    Client.EditValue = _orderModel.Client;
                    Line.EditValue = _orderModel.Line;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载初始数据失败: {ex.Message}");
                // 不抛出异常，继续执行
            }
        }

        /// <summary>
        /// 实体类
        /// </summary>
        public class WorkOrderModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 编码
            /// </summary>
            public string Code { get; set; }
            /// <summary>
            /// 类型  （正常、自建工单）
            /// </summary>
            public string ProductionType { get; set; }
            /// <summary>
            /// 客户  （外键）
            /// </summary>
            public long Client { get; set; }
            /// <summary>
            /// 产品主数据
            /// </summary>
            public string Masterdata { get; set; }
            /// <summary>
            /// 产线 （外键）
            /// </summary>
            public long Line { get; set; }
            /// <summary>
            /// 工序进度
            /// </summary>
            public string Progress { get; set; }
            /// <summary>
            /// 数量
            /// </summary>
            public int ProductionCount { get; set; }
            /// <summary>
            /// 开始时间
            /// </summary>
            public DateTime BeginTime { get; set; }
            /// <summary>
            /// 结束时间
            /// </summary>
            public DateTime EndTime { get; set; }
            /// <summary>
            /// 是否允许有跳工序
            /// </summary>
            public string Whether { get; set; }
            /// <summary>
            /// 上传文件
            /// </summary>
            public string Img { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string ProductionDesc { get; set; }

            /// <summary>
            /// 添加人
            /// </summary>
            public string CreatedBy { get; set; }
        }
        /// <summary>
        /// 实体类
        /// </summary>
        public class WorkOrderUpdateModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 编码
            /// </summary>
            public string Code { get; set; }
            /// <summary>
            /// 类型  （正常、自建工单）
            /// </summary>
            public string ProductionType { get; set; }
            /// <summary>
            /// 客户  （外键）
            /// </summary>
            public long Client { get; set; }
            /// <summary>
            /// 产品主数据
            /// </summary>
            public string Masterdata { get; set; }
            /// <summary>
            /// 产线 （外键）
            /// </summary>
            public long Line { get; set; }
            /// <summary>
            /// 工序进度
            /// </summary>
            public string Progress { get; set; }
            /// <summary>
            /// 数量
            /// </summary>
            public int ProductionCount { get; set; }
            /// <summary>
            /// 开始时间
            /// </summary>
            public DateTime BeginTime { get; set; }
            /// <summary>
            /// 结束时间
            /// </summary>
            public DateTime EndTime { get; set; }
            /// <summary>
            /// 是否允许有跳工序
            /// </summary>
            public string Whether { get; set; }
            /// <summary>
            /// 上传文件
            /// </summary>
            public string Img { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string ProductionDesc { get; set; }

            /// <summary>
            /// 添加人
            /// </summary>
            public string CreatedBy { get; set; }
        }


        /// <summary>
        /// 修改按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Update_Click(object sender, EventArgs e)
        {

            var update = new WorkOrderUpdateModel
            {
                Id = _orderModel.Id, // 使用当前模型的ID
                Code = Code.Text.Trim(),
                ProductionType = ProductionType.Text.Trim(),
                Client = Client.EditValue != null ? Convert.ToInt64(Client.EditValue) : 0,
                Masterdata = Masterdata.Text.Trim(),
                Line = Line.EditValue != null ? Convert.ToInt64(Line.EditValue) : 0,
                Progress = Progress.Text.Trim(),
                ProductionCount = !string.IsNullOrEmpty(ProductionCount.Text) ? Convert.ToInt32(ProductionCount.Text) : 0,
                BeginTime = BeginTime.DateTime,
                EndTime = EndTime.DateTime,
                Whether = Whether.EditValue?.ToString(),
                Img = Img.ToolTip, // 使用保存在ToolTip中的图片URL
                ProductionDesc = ProductionDesc.Text.Trim(),
                CreatedBy = _orderModel.CreatedBy // 保持原创建者不变
            };

            // 发送更新请求
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_OerderUrl);

                // 创建JSON数据
                var json = JsonConvert.SerializeObject(update);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                // 发送PUT请求进行更新
                var response = await client.PutAsync("/api/ProduceModel/UploadWorkorder", content);

                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("更新成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    var errorMessage = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"更新失败：{response.ReasonPhrase}\n{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #region 照片上传

        private async void Photo_Click(object sender, EventArgs e)
        {
            // 调用 XtraOpenFileDialog
            xtraOpenFileDialog1.Filter = "所有文件 (*.*)|*.*"; // 设置筛选器
            if (xtraOpenFileDialog1.ShowDialog() == DialogResult.OK)
            {
                // 用户选了文件，可获取路径
                string filePath = xtraOpenFileDialog1.FileName;

                try
                {
                    // 上传文件并获取返回的URL
                    string fileUrl = await UploadFileAsync(filePath);
                    if (!string.IsNullOrEmpty(fileUrl))
                    {
                        // 将返回的URL保存到Img属性
                        Img.Text = Path.GetFileName(filePath);
                        Img.ToolTip = fileUrl; // 保存完整URL到ToolTip
                        XtraMessageBox.Show("文件上传成功！");
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show("文件上传失败：" + ex.Message);
                }
            }
        }

        /// <summary>
        /// 上传文件到服务器
        /// </summary>
        /// <param name="filePath">本地文件路径</param>
        /// <returns>返回服务器存储的文件URL</returns>
        private async Task<string> UploadFileAsync(string filePath)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://localhost:7223");

                    // 创建MultipartFormDataContent用于上传文件
                    using (var content = new MultipartFormDataContent())
                    {
                        // 读取文件内容
                        var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));

                        // 获取文件名和文件类型
                        string fileName = Path.GetFileName(filePath);
                        string fileExtension = Path.GetExtension(filePath);

                        // 根据文件扩展名设置内容类型
                        switch (fileExtension.ToLower())
                        {
                            case ".jpg":
                            case ".jpeg":
                                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
                                break;
                            case ".png":
                                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
                                break;
                            case ".pdf":
                                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
                                break;
                            default:
                                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                                break;
                        }

                        // 添加文件到请求内容
                        content.Add(fileContent, "file", fileName);

                        // 发送POST请求到文件上传API
                        var response = await client.PostAsync("/api/ProduceModel/UploadWorkorderImage", content);

                        // 检查响应是否成功
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            string responseContent = await response.Content.ReadAsStringAsync();
                            // 解析JSON响应以获取文件URL
                            var result = JsonConvert.DeserializeObject<FileUploadResponse>(responseContent);
                            return result.FileUrl;
                        }
                        else
                        {
                            throw new Exception($"服务器返回错误：{response.StatusCode} - {response.ReasonPhrase}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"上传文件时发生错误：{ex.Message}", ex);
            }
        }

        /// <summary>
        /// 文件上传响应类
        /// </summary>
        public class FileUploadResponse
        {
            /// <summary>
            /// 上传后的文件URL
            /// </summary>
            public string FileUrl { get; set; }

            /// <summary>
            /// 是否成功
            /// </summary>
            public bool Success { get; set; }

            /// <summary>
            /// 消息
            /// </summary>
            public string Message { get; set; }
        }
        #endregion

        //下拉
        private async void Process_Click(object sender, EventArgs e)
        {
            await ShowProcess();
        }

        private async Task ShowProcess()
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_apiProcessUrl}/api/ProcessModel/ShowProcess");
                response.EnsureSuccessStatusCode();


                string responseBody = await response.Content.ReadAsStringAsync();
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                if (jsonObject["pagingData"] != null)
                {
                    string dataJson = jsonObject["pagingData"].ToString();
                    var process = JsonConvert.DeserializeObject<List<ProcessModel>>(dataJson);

                    // 设置数据源
                    Line.Properties.DataSource = process;
                    // 在加载产线数据时
                    Line.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                    Line.Properties.DisplayMember = "ProcessName";  // 数据源中的显示文本字段名
                    Line.Properties.NullText = "请选择所属产线";

                    // 配置GridLookUpEdit的列 - 使用正确的方式
                    if (Line.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                    {
                        // 清除现有列
                        gridView.Columns.Clear();

                        // 添加产线名称列
                        DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                        nameColumn.Caption = "产线名称";
                        nameColumn.FieldName = "ProcessName";
                        nameColumn.Visible = true;
                        nameColumn.VisibleIndex = 0;

                        // 可选：设置列宽
                        nameColumn.Width = 150;

                        // 添加列到网格视图
                        gridView.Columns.Add(nameColumn);

                        // 禁用网格视图的分组面板
                        gridView.OptionsView.ShowGroupPanel = false;

                        // 设置行焦点样式
                        gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                        // 禁用单元格焦点外观
                        gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载产线数据失败: {ex.Message}", "错误");
                throw;
            }

        }
        #region 获取所有客户
        /// 获取所有客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Client_Click(object sender, EventArgs e)
        {
            await ShowClient();
        }

        private async Task ShowClient()
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/api/Customer/GetCustomer");
                response.EnsureSuccessStatusCode();


                string responseBody = await response.Content.ReadAsStringAsync();
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    var process = JsonConvert.DeserializeObject<List<CustomerModel>>(dataJson);

                    // 设置数据源
                    Client.Properties.DataSource = process;
                    // 在加载产线数据时
                    Client.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                    Client.Properties.DisplayMember = "CustomerName";  // 数据源中的显示文本字段名
                    Client.Properties.NullText = "请选择所属客户";

                    // 配置GridLookUpEdit的列 - 使用正确的方式
                    if (Client.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                    {
                        // 清除现有列
                        gridView.Columns.Clear();

                        // 添加产线名称列
                        DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                        nameColumn.Caption = "客户名称";
                        nameColumn.FieldName = "CustomerName";
                        nameColumn.Visible = true;
                        nameColumn.VisibleIndex = 0;

                        // 可选：设置列宽
                        nameColumn.Width = 150;

                        // 添加列到网格视图
                        gridView.Columns.Add(nameColumn);

                        // 禁用网格视图的分组面板
                        gridView.OptionsView.ShowGroupPanel = false;

                        // 设置行焦点样式
                        gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                        // 禁用单元格焦点外观
                        gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载客户数据失败: {ex.Message}", "错误");
                throw;
            }

        }

        private class CustomerModel
        {
            public long Id { get; set; }

            public string CustomerName { get; set; }
        }
        #endregion
    }
}